import {add, batchImport} from '../api/rent-pricebatch.js'
import uploadMedia from '@/components/upload-media'
import roomSelect from '@/components/comm-select/room-select'
import moment from 'moment'

export default {
    name: "price-add",
    components: {uploadMedia,roomSelect},
    data() {
        return {
            // hxf-0806-上传组件使用-----开始--------------
            busId:'',
            uploadFileList: [], // 选中文件列表
            // hxf-0803-busId对应详情的字段名字，用于不同页面字段不同的配置
            //busIdPropertyName: "rentPricebatchId",
            // 不同页面的数据存放对象
            form: {},
            // -------------结束----------------
            formData:{
                //rentPricebatchId:"",
                batch: "",
                assessDate: null,
                validDate: null,
                assessOrg: ""
            },
            importType: "1",
            path: "/app",//process.env.BASE_URL,

            rentPrices: [], //手动输入的列表
            priceFile: null,//批时导入的数据

            fileList: [],

            rules: {
                batch: [
                    {required: true, message: '请输入批次号', trigger: 'blur'},
                    { min: 8, max: 20, message: '长度在 8 到 20 个字符' }
                ],
                assessDate: [
                    { required: true, message: '请选择评估日期', trigger: 'blur' },
                    { validator: this.validateAssessDate, trigger: 'blur' },
                ],
                validDate: [
                    { required: true, message: '请选择有效时间', trigger: 'blur' },
                    { validator: this.validateValidDate, trigger: 'blur' },
                ],
                assessOrg: [{required: true, message: '请输入评估机构', trigger: 'blur'},
                    {
                        min: 1,
                        max: 20,
                        message: '评估机构长度不能超过20个字符'
                    }
                ],
            }
        }
    },
    mounted(){
        if(this.$route.query.importtype!=null){
            this.importType=this.$route.query.importtype;
        }
    },
    methods: {
        // 日期大小校验
        dateVerify(prop) { 
            this.$refs.formData.validateField(prop)
        },
        // 评估日期校验
        validateAssessDate(rule, value, callback) { 
            if (!this.formData.validDate) return callback();
            const startDate = moment(value, "YYYY-MM-DD")
            const endDate = moment(this.formData.validDate, "YYYY-MM-DD")
            let diffDay = endDate.diff(startDate, 'days')
            if (diffDay < 1) {
                return callback(new Error('评估日期必须小于有效日期'));
            }
            return callback();
        },
        // 有效时间校验
        validateValidDate(rule, value, callback) {
            if (!this.formData.assessDate) return callback();
            const startDate = moment(this.formData.assessDate, "YYYY-MM-DD")
            const endDate = moment(value, "YYYY-MM-DD")
            let diffDay = endDate.diff(startDate, 'days')
            if (diffDay < 1) {
                return callback(new Error('有效日期必须大于评估日期'));
            }
            return callback();
         },
        //动态添加行
        addRow() {
            let row = {
                roomCode: "",
                projectName: "",
                area: null,
                price: null

            }
            this.rentPrices.push(row);
        },
        deleteRow(index, row) {
            this.rentPrices.splice(index, 1)
        },

        selectRoom() {
            //弹出选择
            this.$refs.roomSelect.show();
        },

        //物业信息
        completeSelect(selectedData){
            let dataList = selectedData.map(item => {
                const {roomId,buildingArea, propertyName,projectName } = item
                return {
                    roomId,
                    buildingArea,
                    propertyName,
                    projectName,
                    price:null
                }
            })
            this.rentPrices = [...this.rentPrices,...dataList ];
        },
        save() {
            //数据验证
            this.$refs["formData"].validate(valid => {
                if(valid){
                    if (this.rentPrices.length == 0) {
                        this.$message.error("最少添加一条定价明细");
                        return false;
                    } else if (this.rentPrices.some(item => item.price == null || item.price == '')) {
                        this.$message.error("物业评估价不能为空");
                        return false;
                    } else {
                        //先上传附件
                        this.$refs.myUpload.submit();
                    }
                } 
            });
        },
        downTemplate(){
            window.location.href = window.location.origin +'/propertypriceImport.xls'
        },
        onSuccess(response, file, fileList) {
            if (response.code==0) {
                var id = response.data;
                add({ ...this.formData, rentPrices: this.rentPrices, rentPricebatchId: id}).then(response => {
                    if (response.data.code == 0) {
                        this.$message.success("提交成功");
                        this.$router.push({path: '/wy-rent/price/graphic-list'})
                    } else {
                        this.$alert("服务端异常：" + response.message);
                    }
                })
            } else {
                this.err('上传附件返回失败');
            }
        },
        // hxf-0801-上传失败
        onError(err, file, fileList) {
            this.err('上传附件失败'+err)
        },
        goBack(){
            this.$router.back();
        }
    }

}
